package com.lap.analysis.file.handler;

import com.lap.analysis.source.entity.ClassInfo;
import com.lap.analysis.source.entity.FieldInfo;
import com.lap.analysis.source.entity.FileInfo;
import com.lap.analysis.source.entity.MethodInfo;
import com.lap.analysis.tools.Constants;
import com.lap.analysis.tools.ProjectUtil;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

public class ScvFileHandler implements AbstractFileHandler {

  @Override
  public List<FileInfo> execute(ClassInfo classInfo) {
    if (Objects.isNull(classInfo)) return Collections.emptyList();

    return classInfo.getMethods().stream()
        .filter(MethodInfo::isArgMap)
        .map(
            method -> {
              String path = ProjectUtil.getCvsPath(method.getCsvPath());
              String fileName = method.getName() + ".csv";
              String content = getContent(method);
              return new FileInfo(path, fileName, content);
            })
        .toList();
  }

  private String getContent(MethodInfo method) {
    StringBuilder result = new StringBuilder(256);
    String header =
        method.getFields().stream().map(FieldInfo::getDataName).collect(Collectors.joining(","));

    result.append(header);
    result.append(",").append(Constants.RESULT_CODE).append(Constants.WRAP);

    method.getFields().forEach(item -> result.append(","));
    result.append(Constants.WRAP);

    return result.toString();
  }
}
